//
//  BindVC.m
//  timelyRain
//
//  Created by Jiafei Wei on 2016/12/19.
//  Copyright © 2016年 Jiafei Wei. All rights reserved.
//

#import "BindVC.h"
#import "DeviceUtil.h"
#import "HttpTool.h"
#import "RunSucessInfo.h"
#import "SweepCodeBinding.h"
#import "BindInfo.h"
#import "DeviceInfo.h"
#import "BindTool.h"
#import "MainVC.h"
#import "BindFromServer.h"
#import "NetTools.h"
#import "BindNoInternet.h"
#import "AFNetWorking.h"
#import "ChatDemoHelper.h"
@interface BindVC (){
    NSString *phone_number;
    AFNetworkReachabilityManager *mgr;
}
@property (weak, nonatomic) IBOutlet UILabel *bingSatus;
@end

@implementation BindVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getInternetStaus];
}

-(void)bindWatchToserver:(NSString *)watch_sn with:(NSString *)device_sn and:(NSString*)phone_ease_userid by:(NSString*)device_model{
    __weak typeof(self) weakSelf = self;
    NSString *url =[apiUrl stringByAppendingString:bindWatch];
    NSDictionary *paramerter =@{@"watch_sn":watch_sn,@"device_sn":device_sn,@"phone_ease_userid":phone_ease_userid,@"device_model":device_model};
    [HttpTool Post:url parameters:paramerter success:^(id responseObject) {
        //上传给服务器
        NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"bindWatchToserver----=== %@",str);
         RunSucessInfo *success =[RunSucessInfo mj_objectWithKeyValues:responseObject];
        if (success.status) {
            weakSelf.bingSatus.text=@"绑定成功";
            BindInfo *bindInfo =[[BindInfo alloc]init];
            bindInfo.watch_sn=watch_sn;
            bindInfo.phone_number=phone_number;
            bindInfo.watch_ease_userid=phone_number;
            bindInfo.wifi_hot_spot_ssid=@"WPhone 7s";
            [BindTool share].bindInfo =bindInfo;//设置账号
            NSString *jsonBindInfo =[bindInfo mj_JSONString];
            [[NSUserDefaults standardUserDefaults] setObject:jsonBindInfo forKey:@"bindInfo"];
            
            DeviceInfo *deviceInfo =[[DeviceInfo alloc]init];
            deviceInfo.watch_sn =watch_sn;
            deviceInfo.device_sn =device_sn;
            deviceInfo.device_model=@"device_model";
            deviceInfo.phone_ease_userid=phone_ease_userid;
            deviceInfo.phone_model=@"apple";
            [BindTool share].deviceInfo =deviceInfo;
            NSString *jsondeviceInfo =[deviceInfo mj_JSONString];
            [[NSUserDefaults standardUserDefaults] setObject:jsondeviceInfo forKey:@"deviceInfo"];
            [weakSelf loginWithUsername:[BindTool share].deviceInfo.phone_ease_userid password:@"123456"];
        }else{
            weakSelf.bingSatus.text=@"绑定失败";
        }
    } failure:^(NSError *error) {
        
    }];
}

-(void)getBindByServer:(NSString *)device_sn{
     __weak typeof(self) weakSelf = self;
    NSString *url =[apiUrl stringByAppendingString:getBind];
    NSDictionary *paramerter =@{@"device_sn":device_sn};
    [HttpTool GET:url WithHeader:false parameters:paramerter success:^(id responseObject) {
        NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"getBing====%@",str);
        RunSucessInfo *success =[RunSucessInfo mj_objectWithKeyValues:responseObject];
        if (success.status){
            BindFromServer *bindFromServer =[BindFromServer mj_objectWithKeyValues:success.data];
            [weakSelf setBindInfoFromServer:bindFromServer];
            NSLog(@"phone_ease_userid=====#*%@",[BindTool share].deviceInfo.phone_ease_userid);
            [weakSelf loginWithUsername:[BindTool share].deviceInfo.phone_ease_userid password:@"123456"];
        }else{
            NSLog(@"没有绑定啊");
            SweepCodeBinding *codeBing =[[SweepCodeBinding alloc]initWithNibName:@"SweepCodeBinding" bundle:nil];
            [weakSelf.navigationController pushViewController:codeBing animated:YES];
        }
        } failure:^(NSError *error) {
        
    }];
}

- (void)loginWithUsername:(NSString *)username password:(NSString *)password
{
    [self showHudInView:self.view hint:NSLocalizedString(@"login.ongoing", @"Is Login...")];
    __weak typeof(self) weakself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[EMClient sharedClient] loginWithUsername: username password:password completion:^(NSString *aUsername, EMError *aError) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"loginWithUsername");
                if (!aError) {
                    MainVC *main =[[MainVC alloc]init];
                    [ChatDemoHelper shareHelper].mainVC=main;
                    [weakself.navigationController pushViewController:main animated:YES];//登录成功之后获取的好友
                } else {
                    switch (aError.code)
                    {
                            //                    case EMErrorNotFound:
                            //                        TTAlertNoTitle(error.errorDescription);
                            //                        break;
                        case EMErrorNetworkUnavailable:
                            TTAlertNoTitle(NSLocalizedString(@"error.connectNetworkFail", @"No network connection!"));
                            break;
                        case EMErrorServerNotReachable:
                            TTAlertNoTitle(NSLocalizedString(@"error.connectServerFail", @"Connect to the server failed!"));
                            break;
                        case EMErrorUserAuthenticationFailed:
                            TTAlertNoTitle(aError.errorDescription);
                            break;
                        case EMErrorServerTimeout:
                            TTAlertNoTitle(NSLocalizedString(@"error.connectServerTimeout", @"Connect to the server timed out!"));
                            break;
                        default:
                            TTAlertNoTitle(NSLocalizedString(@"login.fail", @"Login failure"));
                            break;
                    }
                }
            });

        }];
});
    
}

-(void)setBindInfoFromServer:(BindFromServer *)server{
    BindInfo *bindInfo =[[BindInfo alloc]init];
    bindInfo.watch_sn =server.watch_sn;
    bindInfo.phone_number =server.watch.phone_number;
    bindInfo.watch_ease_userid =server.watch.watch_ease_userid;
    bindInfo.wifi_hot_spot_ssid =server.watch.wifi_hotspot_ssid;
    bindInfo.datas =server.watch.datas;
    [BindTool share].bindInfo=bindInfo;
    DeviceInfo *deviceInfo =[[DeviceInfo alloc]init];
    deviceInfo.watch_sn =server.watch_sn;
    deviceInfo.device_sn=server.device_sn;
    deviceInfo.device_model =server.device_model;
    deviceInfo.phone_ease_userid =server.phone_ease_userid;
    deviceInfo.phone_model =server.phone_model;
    deviceInfo.data =server.datas;
    [BindTool share].deviceInfo=deviceInfo;
}
-(void)getInternetStaus{
    __weak typeof(self) weakSelf = self;
     mgr = [AFNetworkReachabilityManager sharedManager];
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                NSLog(@"未知网络");
                [weakSelf checkIs];
                break;
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                [weakSelf toNonet];
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                NSLog(@"手机自带网络");
                [weakSelf checkIs];
                 //[weakSelf toNonet];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                NSLog(@"WIFI");
                 [weakSelf checkIs];
                break;
        }
    }];
    [mgr startMonitoring];
}
-(void)checkIs{
    __weak typeof(self) weakSelf1 = self;
     NSString *deviceId =[DeviceUtil getUniqueDeviceIdentifierAsString];
    if (_bindInfo==nil) {
        [weakSelf1 getBindByServer:deviceId];
    }else{
        //绑定的时候就直接登录了啊
        NSArray * infoArray =[_bindInfo componentsSeparatedByString:@"!"];
        NSString *watch_sn =infoArray[0];
        NSString *phone_sn =infoArray[1];
        phone_number=phone_sn;
        phone_sn =[@"phone" stringByAppendingString:phone_sn];
        NSLog(@"watch_sn==%@,phone_sn===%@,deviceId==%@",watch_sn,phone_sn,deviceId);
        _bingSatus.text=@"正在绑定中";
        [weakSelf1 bindWatchToserver:watch_sn with:deviceId and:phone_sn by:@"mobile"];
    }
}
-(void)toNonet{
    BindNoInternet *noNet = [[BindNoInternet alloc]init];
    __weak typeof(self) weakSelf1 = self;
    [weakSelf1.navigationController pushViewController:noNet animated:YES];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    [mgr stopMonitoring];
}
@end
